import axios from "axios";
import { ElLoading } from 'element-plus'
import { ElMessageBox, ElMessage } from "element-plus";
import { diffTokenTime } from '@/util/auth'
import { useLoginStore } from '@/store/app.js'
import router from "@/router/index";
let loadObj = null

const handleCode = (code) => {
    switch (code) {
        case 401:
            ElMessageBox.confirm(
                "您已掉线，或者访问权限出错，请重新登录！",
                "重新登录",
                {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                }
            ).then(async () => {
                console.log('退户')
                const loginStore = useLoginStore();
                loginStore.Logout()
            }).catch(() => { });
            break;
        default:
            ElMessage.error(`后端接口${code}异常`);
            break;
    }
};

//使用create 创建axios实例
const Service = axios.create({
    timeout: 8000,
    //baseURL: "/path1",//http://localhost:8090
    headers: {
        "Content-Type": "application/json;charset=utf-8"
    },
})

//请求之前
Service.interceptors.request.use(config => {

    const accessToken = localStorage.getItem('token');
    if (accessToken) {
        if (diffTokenTime()) {
            const loginStore = useLoginStore();
            loginStore.Logout()
            return Promise.reject(new Error('token失效了'));
        }
        config.headers.Authorization = accessToken;
    }
    loadObj = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    return config
})

//响应拦截
Service.interceptors.response.use(response => {
    // loadObj.close()
    // return response
    loadObj.close()
    const { data, headers, config, status } = response;
    console.log("响应信息")
    console.log(response)
    //文件下载
    if (response.config.responseType === "blob" || response.config.responseType === "arraybuffer") {
        if (status == 200)
            return response;
    }

    // token 过期跳转到登录界面
    if (status === 401) {
        loginStore.Logout();
    }
    console.log(data)
    if (data.code == "200") {
        return data.data;
    }
    else {
        let lmsg = data.msg || "操作失败";
        ElMessage.error(lmsg);
        return Promise.reject(new Error(lmsg));
    }

}, error => {
    loadObj.close()
    const { response, message } = error;
    console.log('打印报错')
    console.log(error)
    if (error.response) {
        const { status } = response;
        handleCode(status);
        return Promise.reject(error);
    } else {
        let { message } = error;
        if (message === "Network Error") {
            message = "后端接口连接异常";
        }
        if (message.includes("timeout")) {
            message = "后端接口请求超时";
        }
        if (message.includes("Request failed with status code")) {
            const code = message.substr(message.length - 3);
            message = "后端接口" + code + "异常";
        }
        ElMessage.error(message || `后端接口未知异常`);
        return Promise.reject(error);
    }
})

//post请求

export const post = config => {
    return Service({
        ...config,
        method: "post",
        data: config.data
    })
}
//get请求

export const get = config => {
    return Service({
        ...config,
        method: "get",
        params: config.params
    })
}
